package org.zhq.server;

import org.zhq.Foo;
import org.zhq.constants.FooGui;
import org.zhq.constants.TCPConstants;
import org.zhq.core.IoContext;
import org.zhq.core.SchedulerImpl;
import org.zhq.impl.IoStealingSelectorProvider;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author zhengquan
 * @date 2018/12/22
 */
public class Server {

    public static void main(String[] args) throws IOException {
        File cachePath = Foo.getCacheDir("server");
        IoContext.setup()
                .ioProvider(new IoStealingSelectorProvider(3))
                .scheduler(new SchedulerImpl(1))
                .start();
        TCPServer tcpServer = new TCPServer(TCPConstants.PORT_SERVER,cachePath);
        boolean isSucceed = tcpServer.start();
        if(!isSucceed){
            System.out.println("start tcp server fail !!!");
            return;
        }
        UDPProvider.start(TCPConstants.PORT_SERVER);

        FooGui gui = new FooGui("Clink-Server", () -> tcpServer.getStatusString());
        gui.doShow();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String str;
        do {
            str = bufferedReader.readLine();
            if(str==null || Foo.COMMAND_EXIT.equalsIgnoreCase(str)){
                break;
            }
            if(str.length()==0){
                continue;
            }
            //广播字符串
            tcpServer.broadcast(str);
        }while (true);

        UDPProvider.stop();
        tcpServer.stop();
        IoContext.close();
        gui.doDismiss();
    }
}
